package com.cat.chapter038;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author cat
 * @description https://leetcode.cn/problems/subsets-ii/
 * @create 2025/6/27 20:47
 * @since JDK17
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Solution01 {

    List<List<Integer>> ans = new ArrayList<>();
    int[] path = new int[11];
    int size;
    int[][] arr = new int[11][2];
    int n;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; ) {
            arr[n][0] = nums[i];
            // 找到一个不相同的数字
            int j = i++;
            while (i < nums.length && nums[i] == nums[i - 1]) {
                i++;
            }
            arr[n++][1] = i - j;
        }
        f(0, 0);
        return ans;
    }

    public void f(int cur, int size) {
//        Arrays.stream(path).limit(size).forEach(list::add);

        if (cur == n) {
            // 数组转换成列表
            ans.add(IntStream.range(0, size).map(i -> path[i]).boxed().collect(Collectors.toList()));
            return;
        }
        // 一个也不拿
        f(cur + 1, size);
        // 拿多个
        for (int i = 1; i <= arr[cur][1]; i++) {
            path[size + i] = arr[cur][0];   // 拿一个
            f(cur + 1, size + i);
        }
        Arrays.stream(path).forEach(System.out::println);
    }

}
